﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Csharpzuoye
{
    //结构和日期
    //用代码证明struct定义的类型是值类型
    //public struct Bed
    //{
    //    public int _id;
    //    public Bed(int id)
    //    {
    //        _id = id;
    //    }
    //}

    public class Program
    {
        //源栈的学费是按周计费的，所以请实现这两个功能： 
        //1.函数GetDate()，能计算一个日期若干（日/周/月）后的日期
        //2.给定任意一个年份，就能按周排列显示每周的起始日期
        //public DateTime(int year, int month, int day);
        //public DateTime AddDays(double value);
        //public static DateTime Parse(string s);
        //Console.WriteLine(DateTime.Parse(now));
        //result = result.AddYears(10);//返回新的日期增加十年
        //Console.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日"));


        //string
        //通过控制台读取用户输入，比如：3月，12周，100天，利用之前作业的GetDate()方法，输出指定时间段后的日期
        public DateTime GetDate(DateTime start, int count, TimeUnit time)
        {
            switch (time)
            {
                case TimeUnit.day:
                    return start.AddDays(count);
                //return datetime = datetime.AddDays(count);
                //不用再声明变量，直接用，变量要有意义
                case TimeUnit.week:
                    return start.AddDays(count * 7);
                case TimeUnit.month:
                    return start.AddMonths(count);
                default:
                    return DateTime.MinValue;
            }
        }
        //2.给定任意一个年份，就能按周排列显示每周的起始日期
        /// <summary>
        /// 获得某一年的第一个星期一
        /// </summary>
        /// <param name="year">指定的年份</param>
        /// <returns>第一个星期一的日期
        public static void ShowWeeks(DateTime start/*,bool includeLastyear,bool includeNextyear*/)
        {
            start = GetFirstMonday(2019);
            int i = 1;
            int currentyear = start.Year;
            while (start.Year == currentyear)
            {
                Console.WriteLine($"第{i}周：,{start.ToString("yyyy年MM月dd日")}-{start.AddDays(6).ToString("yyyy年MM月dd日")}");
                start = start.AddDays(7);
                i++;
            }
        }
        public static DateTime GetFirstMonday(int year)
        {
            ///从该年1月1日起，开始循环，直到找到第一个星期一
            ///判断是不是星期一
            ///如果不是，再加一天
            ///否则，返回当天
            ///找到第一个星期一的日期day
            ///星期一加6天显示一个周期
            DateTime day = new DateTime(year, 1, 1);
            while (day.DayOfWeek != DayOfWeek.Monday)
            {
                day.AddDays(1);
            }
            return day;
        }


        //实现GetCount(string container, string target)方法，可以统计出container中有多少个target 
        //public int IndexOf(String value, int startIndex);
        //返回指定字符串从该实例中指定字符位置开始搜索第一次出现的索引，索引从0开始
        public static void GetCount(string container, string target)
        {
            int index = 0;
            int count = 0;
            for (int i = 0; i < container.Length; i++)
            {
                if ((index = container.IndexOf(target, index)) != -1)
                {
                    count++;
                    Console.WriteLine($"关键字出现的总次数：{count}");
                    index = index + target.Length;
                }
                else
                {
                    break;
                }
            }
        }

        //不使用string自带的Join()方法，定义一个mimicJoin()方法，能将若干字符串character 用指定的分隔符separator连接起来，
        // 比如：mimicJoin("-","a","b","c","d")，其运行结果为：a-b-c-d   StringBuilder
        public static string minicJoin(string separator, string[] character)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < character.Length; i++)
            {
                sb.Append(character[i]);
                if (i == character.Length - 1)
                {
                    break;
                }
                sb.Append(separator);
            }
            return sb.ToString();
        }

        //3.构造一个能装任何数据的数组，并完成数据的读写
        object[] array = new object[] { 5, "acd", 6.24, true, null, };
        //private object[] array;
        //public Object Program(int a, string b, float c, bool d)
        //{
        //    Console.WriteLine(object.Equals(a = 1,b = "ch"));     
        //}

        static void Main(string[] args)
        {
            //利用EF，插入3个User对象
            //通过主键Id找到其中一个User对象
            //修改该User对象的Name属性，将其同步到数据库
            //不加载User对象，仅凭其Id用一句Update SQL语句完成上题
            //删除该用户

            //事务  Helpmoney和User的关系
            //用事务实现帮帮币出售的过程
            //卖方帮帮币足够，扣减数额后成功提交。
            //卖方帮帮币不够，事务回滚，买卖双方帮帮币不变。

            SqlDbContext context = new SqlDbContext();
            var db = context.Database;
            db.EnsureDeleted();
            db.EnsureCreated();

            //记录买卖的两条记录
            int lowestMoney = 50; //低于此数不能交易
            int amount = 25;
            User buyer = context.Users.Where(u => u.Name == "小金").FirstOrDefault();
            HelpMoney buyermoney = context.HelpMoneys.OrderBy(h => h.Id).FirstOrDefault();
            User saler = context.Users.Where(u => u.Name == "小铜").FirstOrDefault();
            HelpMoney salermoney = context.HelpMoneys.OrderBy(h => h.Id).FirstOrDefault();

            using (IDbContextTransaction transaction = context.Database.BeginTransaction())
            {
                if ((salermoney.Usable - lowestMoney) < 0)
                {
                    transaction.Rollback();
                }
                else
                {
                    HelpMoney buyMoney = new HelpMoney
                    {
                        Amount = amount,
                        Usable = buyermoney.Usable - amount
                    };
                    saler.HelpMoneys.Add(buyMoney);

                    HelpMoney saleMoney = new HelpMoney
                    {
                        Amount = amount,
                        Usable = salermoney.Usable + amount
                    };
                    buyer.HelpMoneys.Add(saleMoney);
                    transaction.Commit();

                }

            }

            //EmailMessage emailMessage = new EmailMessage();
            //User zl = new User { Name = "zl", Message = emailMessage, 
            //    Password = "1234", CreateTime = new DateTime(2021,4,6) };

            //context.Add(zl);
            //context.SaveChanges();

            //User user1 = new User
            //{
            //    Name = "小金",
            //    Password = "123",
            //    CreateTime = new DateTime(2020, 1, 8)
            //};

            //User user2 = new User
            //{
            //    Name = "小银",
            //    Password = "234",
            //    CreateTime = new DateTime(2020, 2, 15)
            //};

            //User user3 = new User
            //{
            //    Name = "小铜",
            //    Password = "345",
            //    CreateTime = new DateTime(2020, 3, 27)
            //};
            //context.AddRange(user1, user2, user3);

            //User user4 = context.Find<User>(2);
            //user4.Name = "小破烂";

            //User user5 = new User { Id = 2 };
            //context.Users.Attach(user5);
            //user5.Name = "小邋遢";

            //context.Remove<User>(user5);

            //context.SaveChanges();

            //将User类映射到数据库：
            //使用EF的API直接建库建表删库

            //SqlDbContext context = new SqlDbContext();
            //User user = new User();
            //user.Name = "小金";
            //user.Name = "小银";
            //user.Name = "小铜";

            //context.Users.AddRange(user);
            //context.SaveChanges();

            //使用Migration工具建库建表
            //Migration之后，在User类上添加一列：int FailedTry（尝试登陆失败次数），使用Migration工具：
            //将改动同步到数据库
            //回退数据库到FailedTry添加之前

            //SqlDbContext context = new SqlDbContext();
            //var db = context.Database;
            ////db.Migrate();
            //db.EnsureDeleted();
            //db.EnsureCreated();



            //ADO.NET
            //dBUser.LogOn("小白", "4567");
            //dBUser.Register("小新", "6789",1,6789);
            //DBUser dBUser = new DBUser();
            //IDataParameter ptitle = new SqlParameter("@title", "胖");
            //IDataParameter pauthor = new SqlParameter("@author", "彩虹");
            //IDataParameter pauthor = new SqlParameter("@author", "阳光");
            //IDataParameter pid = new SqlParameter("@pid", 2);

            //dBUser.Publish("INSERT Article(Title,Author) VALUES(@title,@author);", ptitle, pauthor);

            //dBUser.Edit("UPDATE Article SET Title = N'瘦' WHERE Author = @author;", pauthor);

            //Console.WriteLine(dBUser.Show("SELECT Title, PublishTime, Author FROM Article WHERE Id = 2;", pid));

            //dBUser.Show("SELECT Title,PublishTime,Content FROM Article WHERE Author = @author", pauthor);

            //int[] ids = new int[] { 1,3 };
            //IDbCommand[] commands = new IDbCommand[ids.Length];
            //for (int i = 0; i < ids.Length; i++)
            //{
            //    commands[i] = new SqlCommand
            //    {
            //        CommandText = $"DELETE Article WHERE Id = @id "
            //    };
            //    //public SqlParameter(string parameterName, object value);
            //    commands[i].Parameters.Add(new SqlParameter("@id", ids[i]));
            //}

            //dBUser.DeleteRange(commands);

            //1.第一次作业（变量赋值运算）
            //输出两个整数 / 小数的和 / 差 / 积 / 商
            //int a = 10, b = 6;
            //Console.WriteLine(a + b);
            //Console.WriteLine(a - b);
            //Console.WriteLine(a * b);
            //Console.WriteLine(a / b);

            //double c = 1.3,d = 2.8;
            //Console.WriteLine(c + d);
            //Console.WriteLine(c - d);
            //Console.WriteLine(c * d);
            //Console.WriteLine(c / d);


            //电脑计算并输出：[(23 + 7)x12-8]÷6的小数值（挑战：精确到小数点以后2位）
            //float result = Convert.ToSingle((23 + 7) * 12 - 8) / 6;
            //string show = result.ToString("0.00");
            //Console.WriteLine(result);

            //int i = 15;
            //Console.WriteLine(i++);//此时Console.WriteLine(i) i=15
            //i -= 5;//i = 16 - 5
            //Console.WriteLine(i);//i = 11
            //Console.WriteLine(i >= 10);//true

            //Console.WriteLine("i值的最终结果为：" + i);//11

            //int j = 20;
            //Console.WriteLine($"{i}+{j}={i + j}"); //35

            //int k = 10;
            //Console.WriteLine(a > 9 && (!(a < 11) || a > 10));//false
            //Console.Read();


            //定义一个生成数组的方法：int[] GetArray()，其元素随机生成从小到大排列。
            //    Console.WriteLine(array(1, 5, 10));
            //    Console.Read();

            //利用ref调用Swap()方法交换两个同学的床位号
            //    int a = 1, b = 2;
            //    swap(ref a, ref b);
            //    Console.WriteLine(a);
            //    Console.WriteLine(b);

            //找到最高分最低分
            //Console.WriteLine(grade[min]);
            //Console.WriteLine(grade[max]);

            //二分查找
            //int[] numbers = { 1, 3, 5, 7, 9 };      
            //Console.WriteLine(BinarySeek(numbers, 9));

            //显示登录成功或失败
            //Console.WriteLine("请输入验证码");
            //Console.WriteLine("请输入用户名");
            //Console.WriteLine("请输入密码");
            //Console.WriteLine(LogOn("8s97", "hulu", "123456", true)); 

            //计算得到源栈同学的平均成绩（精确到两位小数），方法名GetAverage() 
            //    double[] grade = new double[] { 87, 95, 90, 61, 78, 72 };
            //    Console.WriteLine(average);


            //Student syt = new Student();
            //syt.age = 18;
            //syt = syt.grow(ref syt);
            //Console.WriteLine(syt.age);//age = 1

            //作业里只能改不能读（字段private不可读），只有set没有get！

            //将之前User / Problem / HelpMoney类的字段封装成属性，其中：
            //1.1user.Password在类的外部只能改不能读
            //1.2如果user.Name为“admin”，输入时修改为“系统管理员”
            //1.3roblem.Reward不能为负数 

            //User password = new User();
            //password.Password = "123456";

            //User name = new User();
            //name.Name = "haha";
            //Console.WriteLine(name.Name );

            //Problem reward = new Problem();
            //reward.Reward = 10;
            //Console.WriteLine(reward.Reward);

            //2.调用这些类的有参 / 无参构造函数，生成这些类的对象，调用他们的方法

            //User name = new User();
            //User passward = new User();
            //User code = new User();

            //Problem headline = new Problem();
            //Problem body = new Problem();
            //Problem keyword = new Problem();
            //Problem reward = new Problem();
            //Problem headline = new Problem("body的内容");

            //HelpMoney usable = new HelpMoney();
            //HelpMoney freeze = new HelpMoney();
            //HelpMoney kind = new HelpMoney();
            //HelpMoney change = new HelpMoney();


            //User enter = new User("hulu","12345","jska");

            //Problem solve = new Problem("如何学习编程","吧啦吧啦","C#",11);

            //HelpMoney money = new HelpMoney(66,5,"注册","+3");

            //Problem ky = new Problem(10);
            //ky[0] = "操作系统" ;
            //Console.WriteLine(ky[0]);

            //Content wx = new Content("") ;
            //Console.WriteLine(wx.PublishTime);


            //Content lw = new Article();
            //lw.Release();
            //Problem wx = new Problem();
            //lw.Release();

            //结构和日期
            //用代码证明struct定义的类型是值类型
            //Bed bed;//默认有无参构造函数
            //bed._id = 86;
            //Console.WriteLine(bed._id );


            //枚举和位运算
            //User hl = new User()//只写User报空引用异常
            //{
            //    Tokens = new TokenManager()
            //};
            //hl.Tokens.Add(Token.Admin);
            //hl.Tokens.Add(Token.Blogger);
            //hl.Tokens.Remove(Token.Blogger);
            ////hl.Tokens.Remove(Token.Newbie);
            //Console.WriteLine(hl.Tokens);

            //Object和装箱拆箱
            //2.思考dynamic和var的区别，并用代码予以演示

            //var仅仅只是一个语法糖. var本身并不是一种类型, 而object是是C#中所有类型的父类，dynamic是动态类型。
            //dynamic m = 23;//dynamic类型的变量，不是在编译时候确定实际类型的, 而是在运行时。
            //m = "true";//所以这行能够通过编译，但是会在运行时报错
            //Console.WriteLine(m + 25);

            //object n = 23;//所有的类型都派生自object. 所以它可以赋值为任何类型
            //n = "true";//编译和运行都不会报错
            //           //Console.WriteLine((int)n + 25);//object和dynamic的区别，dynamic要强制类型转换

            //var o = 23;//var声明的变量在赋值的那一刻，就已经决定了是什么类型
            //           //o = "true";//再声明为其他类型，就会出现编译错误
            //Console.WriteLine(o + 25);
            //Console.WriteLine(5 + "acd");

            //栈的调用
            //MimicStack stack = new MimicStack(5);
            //stack.Push(1);
            //stack.Push(2);
            //stack.Push(3);
            //stack.Push(4);
            //stack.Push(5);
            //stack.Pop();

            //2.在Content之外封装一个方法，可以修改Content的CreateTime和PublishTime
            //public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr);
            //public void SetValue(object? obj, object? value);  （参数，将设置其属性值的对象）
            //public PropertyInfo? GetProperty(string name, Type? returnType);
            //Type typeInfo = price.GetType();
            //Type typeInfo = typeof(Content);

            //2.在Content之外封装一个方法，可以修改Content的CreateTime和PublishTime
            //DateTime dateTime = new DateTime(2019,4,5);
            //Content content = new Content("Study");
            //new Time().GetPublishTime(content, dateTime);

            //5.用反射获取Publish()上的特性实例，输出其中包含的信息
            //Attribute attribute = HelpMoneyChangedAttribute.GetCustomAttribute(
            //    typeof(Problem).GetMethod("Publish"),
            //    typeof(HelpMoneyChangedAttribute)
            //    );
            //Console.WriteLine(((HelpMoneyChangedAttribute)attribute).Message);


            //点赞点踩
            //new Article().AgreeBy(new User());
            //new Article().DisagreeBy(new User());

            //显式实现接口的调用
            //ISendMessage user = new User();
            //user.Send();

            //IChat chat = new User();
            //chat.Send();

            //string
            //3月，12周，100天
            //DateTime date = new DateTime(2020, 10, 3);
            //Console.WriteLine(date.AddDays(100));
            //Console.WriteLine(date.AddDays(12 * 7));
            //Console.WriteLine(date.AddMonths(3));
            ////password
            //Console.WriteLine(User.PasswordRule("301~*36"));
            ////若干字符串character 用指定的分隔符separator连接起来
            //Console.WriteLine(Program.minicJoin("-", new string[] { "a", "b", "c", "d" }));

            ////GetCount()
            //GetCount("1356795678934556727364287", "56");

            //在现有作业的基础上，观察一起帮的文章板块，以此为蓝本，补充（如果还没有的话）声明：

            //Article article = new Article();
            //Comment comment = new Comment();
            //Appraise appraise = new Appraise();
            //Keyword keyword = new Keyword();

            //comment.Article = article;
            //article.Comments = new List<Comment> { comment };

            //article.Appraise = appraise;
            //comment.Appraise = appraise;
            //article.Keywords = new List<Keyword> { keyword };
            //keyword.Articles = new List<Article> { article };
            //    评论（Comment）类
            //    评价（Appraise）类：包括“赞（Agree）”和“踩（Disagree）”
            //    关键字（Keyword）类

            //并构建以下关系：

            //    一篇文章可以有多个评论
            //    一个评论必须有一个它所评论的文章
            //    每个文章和评论都有一个评价
            //    一篇文章可以有多个关键字，一个关键字可以对应多篇文章

            //在之前“文章 / 评价 / 评论 / 用户 / 关键字”对象模型的基础上，添加相应的数据，然后完成以下操作：
            //找出“飞哥”发布的文章
            //找出2019年1月1日以后“小鱼”发布的文章
            //按发布时间升序 / 降序排列显示文章
            //统计每个用户各发布了多少篇文章
            //找出包含关键字“C#”或“.NET”的文章
            //找出评论数量最多的文章
            //找出每个作者评论数最多的文章

            //找出每个作者最近发布的一篇文章
            //为求助（Problem）添加悬赏（Reward）属性，并找出每一篇求助的悬赏都大于5个帮帮币的求助作者

            //        User fg = new User { Name = "飞哥"/*, Problems = new List<Problem> { Help, Edit, Operation }*/ };
            //        User fish = new User { Name = "小鱼"/*, Problems = new List<Problem> { Invoke, Error }*/ };
            //        IEnumerable<User> users = new List<User> { fg, fish };

            //        Problem Help = new Problem { User = fg ,Reward = 6};
            //        Problem Edit = new Problem { User = fg ,Reward = 14};
            //        Problem Operation = new Problem { User = fg, Reward = 15 };
            //        Problem Invoke = new Problem { User = fish, Reward = 7 };
            //        Problem Error = new Problem { User = fish, Reward = 8 };
            //        IEnumerable<Problem> problems = new List<Problem> { Help, Edit, Operation, Invoke, Error };

            //        Appraise Agree = new Appraise { Name = "Agree" };
            //        Appraise Disagree = new Appraise { Name = "Disagree" };
            //        IEnumerable<Appraise> appraises = new List<Appraise> { Agree, Disagree };

            //        Keyword Csharp = new Keyword { Name = "Csharp" };
            //        Keyword JavaScript = new Keyword { Name = "JavaScript" };
            //        Keyword SQL = new Keyword { Name = "SQL" };
            //        Keyword Html = new Keyword { Name = "Html" };
            //        Keyword NET = new Keyword { Name = "NET" };
            //        IEnumerable<Keyword> keywords = new List<Keyword> { Csharp, JavaScript, SQL, Html, NET };

            //        Comment Wonderful = new Comment { Name = "Wonderful" };
            //        Comment Great = new Comment { Name = "Great" };
            //        Comment Good = new Comment { Name = "Good" };
            //        Comment JustSoSo = new Comment { Name = "JustSoSo" };
            //        Comment Bad = new Comment { Name = "Bad" };
            //        IEnumerable<Comment> comments = new List<Comment> { Wonderful, Great, Good, JustSoSo, Bad };

            //        Article Study = new Article
            //        {
            //            Name = "Study",
            //            User = fg,
            //            Time = new DateTime(2018, 9, 9),
            //            Appraise = Agree,
            //            Keywords = new List<Keyword> { Csharp, JavaScript, SQL, Html, NET },
            //            Comments = new List<Comment> { Great, Good, Wonderful, JustSoSo }
            //        };
            //        Article Think = new Article
            //        {
            //            Name = "Think",
            //            User = fish,
            //            Time = new DateTime(2018, 4, 25),
            //            Appraise = Disagree,
            //            Keywords = new List<Keyword> { Csharp, Html },
            //            Comments = new List<Comment> { JustSoSo }
            //        };
            //        Article Belief = new Article
            //        {
            //            Name = "Belief",
            //            User = fish,
            //            Time = new DateTime(2019, 5, 1),
            //            Appraise = Agree,
            //            Keywords = new List<Keyword> { NET, SQL },
            //            Comments = new List<Comment> { Wonderful, Bad, Good }
            //        };
            //        Article Begin = new Article
            //        {
            //            Name = "Begin",
            //            User = fg,
            //            Time = new DateTime(2019, 2, 17),
            //            Appraise = Agree,
            //            Keywords = new List<Keyword> { Csharp, NET, Html },
            //            Comments = new List<Comment> { JustSoSo, Great }
            //        };
            //        Article Question = new Article
            //        {
            //            Name = "Question",
            //            User = fg,
            //            Time = new DateTime(2019, 6, 22),
            //            Appraise = Agree,
            //            Keywords = new List<Keyword> { JavaScript },
            //            Comments = new List<Comment> { Good, Bad, Wonderful }
            //        };
            //        IEnumerable<Article> articles = new List<Article> { Study, Think, Belief, Begin, Question };

            //        //将之前作业的Linq查询表达式用Linq方法实现
            //        //找出“飞哥”发布的文章

            //        //IEnumerable<Article> articlesByfg = from a in articles
            //        //                                    where a.User == fg
            //        //                                    select a;
            //        var result = articles.Where(a => a.User == fg);
            //        foreach (var item in result)
            //        {
            //            Console.WriteLine($"{item.User.Name}发布的文章：{item.Name}");
            //        }
            //        //找出2019年1月1日以后“小鱼”发布的文章
            //        DateTime minicNow = new DateTime(2019, 1, 1);
            //        //IEnumerable<Article> articlesByfish = from b in articles
            //        //                                      where b.User == fish && b.Time > minicNow
            //        //                                      select b;
            //        var result1 = articles.Where(a => a.User == fish && a.Time > minicNow);
            //        foreach (var item in result1)
            //        {
            //            Console.WriteLine($"{item.User.Name}在{item.Time}以后发布的文章：{item.Name}");
            //        }
            //        //按发布时间升序 / 降序排列显示文章
            //        //IEnumerable<Article> articlesByTime = from c in articles
            //        //                                      orderby c.Time descending
            //        //                                      select c;
            //        var result2 = articles.OrderByDescending(a => a.Time);
            //        foreach (var item in result2)
            //        {
            //            Console.WriteLine($"{item.Time}:{item.Name}");
            //        }
            //        //统计每个用户各发布了多少篇文章
            //        //var stat = from d in articles
            //        //           group d by d.User
            //        //           into gm
            //        //           select new
            //        //           {
            //        //               gm.Key,
            //        //               Count = gm.Count()//统计有多少篇文章
            //        //           };
            //        var result3 = articles.GroupBy(a => a.User);
            //        var stat = result3.Select(r => new
            //        {
            //            r.Key.Name,
            //            Count = r.Count()
            //        });
            //        foreach (var item in stat)
            //        {
            //            Console.WriteLine(item.Name + ":" + item.Count);
            //        }

            //        //找出包含关键字“C#”或“.NET”的文章
            //        //var articlesKeyword = from e in articles
            //        //                      where e.Keywords.Contains(Csharp) || e.Keywords.Contains(NET)
            //        //                      select e;
            //        var result4 = articles.Where(a => a.Keywords.Contains(Csharp) || a.Keywords.Contains(NET));
            //        foreach (var item in result4)
            //        {
            //            Console.WriteLine(item.Name);
            //        }

            //        //找出评论数量最多的文章
            //        //先找每篇文章有多少个评论 排序取最多的
            //        //var articlesMax = (from f in articles
            //        //                   orderby f.Comments.Count descending
            //        //                   select f).First();
            //        var result5 = articles.OrderByDescending(a => a.Comments.Count()).First();
            //        Console.WriteLine(result5.Name);

            //        //找出每个作者评论数最多的文章
            //        //先按作者给文章分组
            //        //每个文章有多少评论
            //        var result6 = from a in articles
            //                      group a by a.User
            //                           into ga
            //                      select new
            //                      {
            //                          ga.Key,
            //                          comment = (from b in ga
            //                                     orderby b.Comments.Count descending
            //                                     select b).First()
            //                      };


            //        foreach (var item in result6)
            //        {
            //            Console.WriteLine($"{item.Key.Name} : { item.comment.Name}");
            //        }

            //        //找出每个作者最近发布的一篇文章 
            //        var result7 = from a in articles
            //                      group a by a.User
            //                           into ga
            //                      select new
            //                      {
            //                          ga.Key,
            //                          Time = (from b in ga
            //                                  orderby b.Time descending
            //                                  select b).First()
            //                      };
            //        foreach (var item in result7)
            //        {
            //            Console.WriteLine($"{item.Key.Name} : {item.Time.Name}");
            //        }

            //        //找出每一篇求助的悬赏都大于5个帮帮币的求助作者
            //        //求助根据作者分组
            //        var result8 = problems.GroupBy(p => p.User)
            //            .Where(g => g.Min(a => a.Reward) > 5)
            //            ;
            //        var stat1 = result8.Select(r => r.Key);
            //        foreach (var item in stat1)
            //        {
            //            Console.WriteLine(item.Name);
            //        }



            //        //让之前的双向链表，能够：被foreach迭代
            //        //调用扩展方法Max()：能够返回之前双向链表中存贮着最大值的节点

            //        DLinkNode<int> node1 = new DLinkNode<int> { Value = 1 };
            //        DLinkNode<int> node2 = new DLinkNode<int> { Value = 2 };
            //        DLinkNode<int> node3 = new DLinkNode<int> { Value = 3 };
            //        DLinkNode<int> node4 = new DLinkNode<int> { Value = 4 };
            //        DLinkNode<int> node5 = new DLinkNode<int> { Value = 5 };

            //        node1.AddAfter(node2);
            //        node2.AddAfter(node3);
            //        node3.AddAfter(node4);
            //        node4.AddAfter(node5);


            //        foreach (var item in node1)
            //        {
            //            Console.WriteLine(item.Value);
            //        }
            //        var maxValue = node5.MyMax();
            //        Console.WriteLine(maxValue);

            //        //异常
            //        //4.ContentService中无论是否捕获异常，均要Console.WriteLine() 输出：XXXX年XX月XX日 XX点XX分XX秒（当前时间），请求发布内容（Id=XXX）
            //        //    在Main()函数调用ContentService时，捕获一切异常，并记录异常的消息和堆栈信息

            //        try
            //        {
            //            Content content = new Content();
            //            content.Publish();
            //        }
            //        catch (Exception e)
            //        {
            //            Console.WriteLine($"XXXX年XX月XX日 XX点XX分XX秒（当前时间），请求发布内容（Id=XXX）{e.ToString()}");
            //            //throw;
            //        }

            //    }
            //}

            ////扩展（extension）方法 
            ////调用扩展方法Max()：能够返回之前双向链表中存贮着最大值的节点

            //public static class ExtensionMethod 
            //{
            //    public static T MyMax<T>(this DLinkNode<T> source) where T : IComparable<T>
            //    {
            //        T max = default;
            //        foreach (var item in source)
            //        {
            //            if (item.Value.CompareTo(max) > 0 )
            //            {
            //                max = item.Value;
            //            }
            //        }
            //        return max;
            //    }
        }
    }
}




